'''
Created on 2011-12-31

@author: alex.ren
'''

import time
import threading
import interface
import monitor
import robot

orbit_file_name = 'c:/swpy.txt'

locus = []

leftKey = 0x41
rightKey = 0x44
upKey = 0x57
downKey = 0x53

con = threading.Condition()

def init():
    f = file(orbit_file_name, 'r')
    lines = f.readlines()
    for line in lines:
        pos = line.split(',')
        locus.append((int(pos[0]), int(pos[1].replace('\n',''))))

def doWork():
    init()
    while True:
        if robot.isResting() == True:
            time.sleep(5)
        else:
            move()
            robot.updateRest(True)

def doPause():
    if monitor.isPaused() == True:
        con.acquire()
        con.wait()
        con.release()
        
def notify():
    con.acquire()
    con.notify()
    con.release()

def move():
    for pos in locus:
        doPause()
        moveTo(pos)
        time.sleep(0.3)
                
def moveTo(pos):
    x = pos[0]
    y = pos[1]
    moveX(x)
    moveY(y)

def moveX(x):
    while True:
        time.sleep(0.1)
        cx = interface.getX()
        deltaX = x - cx
        key = None
        if deltaX > 0:
            key = rightKey
        else:
            key = leftKey
        if key != None and deltaX != 0:
            interface.pressAt(key)
        if deltaX == 0:
            break
        
def moveY(y):
    while True:
        time.sleep(0.1)
        cy = interface.getY()
        deltaY = y - cy
        key = None
        if deltaY > 0:
            key = downKey
        else:
            key = upKey
        if key != None and deltaY != 0:
            interface.pressAt(key)
        if deltaY == 0:
            break